import { createRouter, createWebHistory, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores/user'
import Layout from '@/layout/index.vue'

NProgress.configure({ showSpinner: false })

// 使用 glob 导入所有视图组件
const views = import.meta.glob('../views/**/*.vue')

/**
 * 静态路由
 */
const staticRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  }
]

/**
 * 404，401 路由
 */
const errorRoutes = [
  {
    path: '/:path(.*)*',
    name: 'notFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '404',
      hidden: true
    }
  },
  {
    path: '/401',
    name: 'noPower',
    component: () => import('@/views/error/401.vue'),
    meta: {
      title: '401',
      hidden: true
    }
  }
]

/**
 * 动态路由
 */
const dynamicRoutes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    meta: { title: '首页' },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页' }
      },
      {
        path: '/personal',
        name: 'Personal',
        component: () => import('@/views/personal/index.vue'),
        meta: { title: '个人中心', hidden: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()

  const token = sessionStorage.getItem('token')

  // 如果是登录或者注册页面且没有token，则直接进入
  if ((to.path === '/login' || to.path === '/register') && !token) {
    next()
  } else {
    // 如果没有 token，则重定向到登录页面
    if (!token) {
      next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`)
      sessionStorage.clear()
    }
    // 如果有 token 并且是登录或者 注册页面，则重定向到首页
    else if (token && (to.path === '/login' || to.path === '/register')) {
      next('/')
    }
    // 如果有 token 并且不是登录或者注册页面，则正常跳转
    else {
      // 获取用户信息
      const userStore = useUserStore()
      const { user, menus } = storeToRefs(userStore)
      if (!user.value || !user.value.id) {
        await userStore.getInfo()
        // console.log('user', user.value)

        // 获取导航菜单
        await userStore.getMenuNav()
        // console.log('nav', menus.value)

        // 转换路由
        menus.value.forEach((item) => {
          dynamicRoutes[0].children.push(convertMenuToRoute(item))
        })

        // 添加动态菜单
        dynamicRoutes.forEach((item) => {
          router.addRoute(item)
        })

        // 添加错误菜单
        errorRoutes.forEach((item) => {
          router.addRoute(item)
        })

        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  }
})

router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})

function convertPathToComponentName(path) {
  // 移除开头的斜杠并按斜杠分割
  const parts = path.replace(/^\//, '').split('/')

  // 如果最后一个部分是 'index'，则移除它
  if (parts[parts.length - 1] === 'index') {
    parts.pop()
  }

  // 将每个部分的首字母大写并连接起来
  return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('')
}

function convertMenuToRoute(menu) {
  // 构建路由
  const route = {
    path: menu.path,
    meta: {
      title: menu.name,
      icon: menu.icon,
      hidden: menu.hidden
    }
  }

  // 设置组件
  if (menu.component) {
    route.name = convertPathToComponentName(menu.component)

    // 正确处理异步组件加载
    let componentPath = menu.component

    // 如果不是 / 开头，则加上 /
    if (!componentPath.startsWith('/')) {
      componentPath = '/' + componentPath
    }

    // 如果不是 .vue 结尾，则加上 .vue
    if (!componentPath.endsWith('.vue')) {
      componentPath += '.vue'
    }

    const fullPath = '../views' + componentPath

    // 检查组件是否存在，并正确返回异步组件
    if (views[fullPath]) {
      route.component = views[fullPath]
    } else {
      console.warn(`Component not found: ${fullPath}`)
      // 可以返回一个默认的错误组件
      route.component = () => import('@/views/error/404.vue')
    }
  }

  // 设置重定向
  if (menu.redirect) {
    route.redirect = menu.redirect
  }

  // 处理子菜单
  if (menu.children && menu.children.length > 0) {
    const childrenRoutes = menu.children.map(convertMenuToRoute).filter((route) => route !== null)

    if (childrenRoutes.length > 0) {
      route.children = childrenRoutes
    }
  }

  return route
}

export default router
